#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from pymongo import MongoClient


def ListOrganization():
    import sys
    default_encoding = 'utf-8'
    if sys.getdefaultencoding() != default_encoding:
        reload(sys)
        sys.setdefaultencoding(default_encoding)

    DB_NAME = "organization"
    COLLECTION_NAME = "organization"

    connection = MongoClient('localhost', 27017)
    db = connection[DB_NAME]
    collection = db[COLLECTION_NAME]

    result_province = collection.distinct("province", {"country": "China"})
    for item_province in result_province:
        if item_province != None:
            result_city = collection.distinct("city", {"country": "China", "province": item_province})
            for item_city in result_city:
                if item_city != None:
                    result1 = collection.distinct("uni_org",
                                                  {"country": "China", "province": item_province, "city": item_city})
                    for item1 in result1:
                        if item1 != None:
                            print "China\t" + item_province + "\t" + item_city + "\t" + item1
            result2 = collection.distinct("uni_org",
                                          {"country": "China", "province": item_province, "city": {"$exists": 0}})
            for item2 in result2:
                if item2 != None:
                    print "China\t" + item_province + "\t\t" + item2
    result3 = collection.distinct("uni_org", {"country": "China", "province": {"$exists": 0}})
    for item3 in result3:
        if item3 != None:
            print "China\t\t\t" + item3
    connection.close()


    # for result in results:
    #     line=""
    #     if result.has_key("id"):
    #         line+=str(result["id"])
    #     line+="\t"
    #     if result.has_key("org_id"):
    #         line+=str(result["org_id"])
    #     line+="\t"
    #     if result.has_key("country"):
    #         line+=result["country"]
    #     line+="\t"
    #     if result.has_key("province"):
    #         line+=result["province"]
    #     line+="\t"
    #     if result.has_key("city"):
    #         line+=result["city"]
    #     line+="\t"
    #     if result.has_key("uni_org_type"):
    #         line+=result["uni_org_type"]
    #     line+="\t"
    #     if result.has_key("uni_org"):
    #         line+=result["uni_org"]
    #     line+="\t"
    #     if result.has_key("org"):
    #         line+=result["org"]
    #     print line


if __name__ == "__main__":
    ListOrganization()
